import 'dart:async';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_09_game/config/app_color.dart';
import 'package:flutter_09_game/config/history_route_ovserver.dart';
import 'package:flutter_09_game/generated/assets.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/http/http_export.dart';
import 'package:flutter_09_game/pages/home/models/model_notice_active.dart';
import 'package:flutter_09_game/utils/loading/loading_utils.dart';
import 'package:flutter_09_game/utils/shared/shared_export.dart';
import 'package:flutter_09_game/utils/shared/shared_storage.dart';
import 'package:flutter_09_game/widgets/button/debounce_gesture_detector.dart';
import 'package:flutter_09_game/widgets/image/auto_image.dart';
import 'package:flutter_09_game/widgets/image/image_view.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

/// 首页公告弹窗组件
/// 根据Figma设计实现居中弹窗显示公告图片，支持轮播和24小时内不提示
class NoticePopupDialog extends StatefulWidget {
  const NoticePopupDialog({
    super.key,
    required this.notices,
  });
  static String name = 'NoticePopupDialog';

  final List<ModelNoticeActive> notices;

  /// 显示公告弹窗
  static Future<void> show(List<ModelNoticeActive> notices) async {

    return await Get.dialog(
      NoticePopupDialog(notices: notices),
      // barrierDismissible: false,
      name: NoticePopupDialog.name,
      barrierColor: Colors.black.withOpacity(0.5),
    );
  }

  @override
  State<NoticePopupDialog> createState() => _NoticePopupDialogState();
}

class _NoticePopupDialogState extends State<NoticePopupDialog> {
  int currentIndex = 0;
  bool noShowFor24Hours = false;

  /// 获取所有图片URL列表
  List<String> get imageUrls {
    List<String> urls = [];
    for (var notice in widget.notices) {
      if (notice.image != null && notice.image!.isNotEmpty) {
        // 支持单张图片或多张图片（逗号分隔）
        if (notice.image!.contains(',')) {
          urls.addAll(notice.image!.split(',').map((e) => e.trim()));
        } else {
          urls.add(notice.image!);
        }
      }
    }
    return urls;
  }

  @override
  Widget build(BuildContext context) {
    final images = imageUrls;
    if (images.isEmpty) {
      return const SizedBox.shrink();
    }

    return Center(
      child: Container(
        width: 315.w,
        decoration: const BoxDecoration(
          color: Colors.transparent,
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Stack(
              children: [
                // 图片轮播区域
                _buildImageCarousel(images),
                // 关闭按钮
                _buildCloseButton(),
                // 轮播指示器
                if (images.length > 1) _buildIndicators(images.length),
              ],
            ),
            // 12.verticalSpaceFromWidth,
            // 24小时内不提示选项
            _build24HourOption(),
          ],
        ),
      ),
    );
  }

  /// 构建图片轮播
  Widget _buildImageCarousel(List<String> images) {
    return CarouselSlider.builder(
      options: CarouselOptions(
        height: 500.w,
        autoPlay: images.length > 1,
        // 单张图片时不自动播放
        autoPlayInterval: const Duration(seconds: 3),
        autoPlayAnimationDuration: const Duration(milliseconds: 300),
        autoPlayCurve: Curves.easeInOut,
        enlargeCenterPage: false,
        enableInfiniteScroll: images.length > 1,
        viewportFraction: 1.0,
        onPageChanged: (index, reason) {
          setState(() {
            currentIndex = index;
          });
        },
      ),
      itemCount: images.length,
      itemBuilder: (context, index, realIndex) {
        return ImageView(
          imageUrl: images[index],
          // width: 315.w,
          width: double.infinity,
          radius: 12.w,
          // fit: BoxFit.fitWidth,
        );
        // return _buildImageItem(images[index]);
      },
    );
  }

  /// 构建关闭按钮
  Widget _buildCloseButton() {
    return Positioned(
      top: 0,
      right: 0,
      child: SizedBox(
        height: 46.w,
        child: Align(
          alignment: Alignment.centerRight,
          child: DebounceGestureDetector(
            onTap: () => _handleClose(),
            child: Padding(
              padding: EdgeInsets.only(top: 8.w, right: 8.w),
              child: AutoImage(
                Assets.commonCancelBtn,
                width: 32.w,
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 构建轮播指示器
  Widget _buildIndicators(int count) {
    return Positioned(
      bottom: 8.w,
      left: 0,
      right: 0,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: List.generate(
          count,
          (index) => Container(
            margin: EdgeInsets.symmetric(horizontal: 2.w),
            width: currentIndex == index ? 6.w : 6.w,
            height: 6.w,
            decoration: BoxDecoration(
              color: currentIndex == index
                  ? AppColor.textPrimary.withOpacity(0.94)
                  : AppColor.textPrimary.withOpacity(0.5),
              borderRadius: BorderRadius.circular(3.w),
            ),
          ),
        ),
      ),
    );
  }

  /// 构建24小时内不提示选项
  Widget _build24HourOption() {
    return GestureDetector(
      onTap: () => _toggle24HourOption(),
      behavior: HitTestBehavior.opaque,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          AutoImage(
            noShowFor24Hours
                ? Assets.commonCheckboxSel
                : Assets.commonCheckboxNorDialog,
            width: 16.w,
          ),
          8.horizontalSpace,
          Text(
            LocaleKeys.notShowIn24h.tr,
            style: TextStyle(
              fontSize: 12.sp,
              color: AppColor.textPrimary.withOpacity(0.94),
            ),
          ),
        ],
      ).marginAll(12.w),
    );
  }

  /// 切换24小时内不提示状态
  void _toggle24HourOption() async {
    setState(() {
      noShowFor24Hours = !noShowFor24Hours;
    });
    HttpResponse response = await HttpManager().post(
      API.postNoticeForbidden,
      uiType: HttpUIType.loading
    );
    if (response.isSuccess) {
    // 设置成功
      LoadingUtils.showToast(LocaleKeys.setSuccess.tr);
      // Get.back();
      routeHistoryObserver.removeName(NoticePopupDialog.name);
      // setState(() {
      //   noShowFor24Hours = !noShowFor24Hours;
      // });
    }

    // _save24HourNoShowState();
  }

  /// 处理关闭弹窗
  void _handleClose() {
    Get.back();
  }

  /// 保存24小时内不显示状态
// void _save24HourNoShowState() {
//   final expireTime = DateTime.now().add(const Duration(hours: 24));
//   SharedStorage().prefs.setInt(
//         SharedKey.noticeNoShowUntil,
//     noShowFor24Hours ?  expireTime.millisecondsSinceEpoch : 0  ,
//       );
//   LoadingUtils.showToast(LocaleKeys.operationSuccess.tr);
// }
}
